import requests
from parsel import Selector
from typing import Dict, List
import time
import random


def fetch_all_data(url: str) -> Dict[str, List]:
    """获取实时数据 + 历史数据（增强版）"""
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "Referer": "https://www.zzwbgg.com/",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
    }

    result = {
        "realtime": {},
        "history": [],
        "status": "success"
    }

    try:
        # 添加随机延迟避免封禁
        time.sleep(random.uniform(1, 3))

        response = requests.get(
            url,
            headers=headers,
            timeout=15,
            verify=False  # 仅测试环境使用，正式环境应配置证书
        )
        response.raise_for_status()

        # 验证响应内容
        if len(response.text) < 5000:
            raise ValueError("响应内容过短，可能被反爬")

        sel = Selector(text=response.text)

        # 解析实时数据（带备用选择器）
        realtime_data = {}
        selectors = {
            "issue": [
                ".newissue-box-num span::text",
                ".issue-number::text"  # 备用选择器
            ],
            "sum": [
                ".newissue-box-result > span::text",
                ".sum-value::text"
            ],
            "codes": [
                ".newissue-box-result-item span::text, .newissue-box-result-item i::text",
                ".number-item::text"
            ]
        }

        # 尝试多个选择器
        for key in selectors:
            for selector in selectors[key]:
                elements = sel.css(selector).getall()
                if elements:
                    realtime_data[key] = elements
                    break

        # 验证必须字段
        required_fields = {
            "issue": "当前期号",
            "sum": "总和值",
            "codes": "号码组合"
        }

        for field, name in required_fields.items():
            if not realtime_data.get(field):
                raise ValueError(f"缺失必要字段: {name}")

        # 构建实时数据
        result["realtime"] = {
            "当前期号": "".join(realtime_data["issue"]).strip(),
            "总和": "".join(realtime_data["sum"]).strip(),
            "开奖号码": "".join(realtime_data["codes"] + realtime_data["sum"]).strip()
        }

        # 解析历史数据（带容错）
        history_data = []
        history_items = sel.css('div.tabbar-history-item-content-item') or sel.css('.history-item')
        for item in history_items:
            try:
                history_data.append({
                    "期号": item.xpath('.//span[1]/text()').get("").strip(),
                    "时间": item.xpath('.//span[2]/text()').get("").strip(),
                    "号码": item.xpath('.//span[3]/text()').get("").strip()
                })
            except Exception as e:
                print(f"解析历史记录失败: {str(e)}")
                continue

        result["history"] = history_data

    except requests.exceptions.RequestException as e:
        result["status"] = f"请求错误: {str(e)}"
    except ValueError as e:
        result["status"] = f"数据验证失败: {str(e)}"
    except Exception as e:
        result["status"] = f"未知错误: {str(e)}"
        if 'response' in locals():
            with open("error.html", "w", encoding="utf-8") as f:
                f.write(response.text)
    finally:
        return result


# 安全测试示例
if __name__ == "__main__":
    target_url = "https://www.zzwbgg.com"

    print(f"开始抓取: {target_url}")
    start_time = time.time()

    data = fetch_all_data(target_url)

    print(f"\n耗时: {time.time() - start_time:.2f}秒")
    print(f"状态: {data['status']}")


    # 安全访问数据
    def safe_get(data, keys, default="N/A"):
        """多层字典安全访问"""
        for key in keys:
            if isinstance(data, dict) and key in data:
                data = data[key]
            else:
                return default
        return data or default


    print("\n===== 实时开奖数据 =====")
    print(f"期号: {safe_get(data, ['realtime', '当前期号'])}")
    print(f"号码组合: {safe_get(data, ['realtime', '开奖号码'])}")
    print(f"总和: {safe_get(data, ['realtime', '总和'])}")

    print("\n===== 最近历史记录 =====")
    for idx, item in enumerate(data["history"][:5]):
        print(f"{idx + 1}. {item.get('期号', 'N/A')} | {item.get('时间', 'N/A')} | {item.get('号码', 'N/A')}")